﻿
'Copyright 2010 Brian L. Crawford

'Licensed under the Apache License, Version 2.0 (the "License");
'you may not use this file except in compliance with the License.
'You may obtain a copy of the License at

'    http://www.apache.org/licenses/LICENSE-2.0

'Unless required by applicable law or agreed to in writing, software
'distributed under the License is distributed on an "AS IS" BASIS,
'WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
'See the License for the specific language governing permissions and
'limitations under the License.

'This software uses Microsoft .Net framework used with permission from      
'Microsoft. Microsoft, .Net Framework, Visual Studio, Visual Basic, Visual C++ 
'remain the trademark and copyright of Microsoft and are subject to their 
'individual licenses.

Imports System.Windows.Forms
Imports System.Threading
Imports System.Timers
Imports System.ComponentModel
Imports System.IO

Public Class stForm
    Inherits Form
    Dim checkboxstatus, folder1status, folder2status As Boolean
    Dim Savepath As String
    Dim strDefaultRemove As String = "Model"
   
    Public Sub New()
        'Define Container name and dimensions
        Me.Text = "EDDS File Utilities"
        Me.Size = New Size(780, 656)
        Me.CenterToScreen()
        ' Create ToolStripPanel controls.
        Dim tspTop As New ToolStripPanel()

        ' Dock the ToolStripPanel controls to the edges of the form.
        tspTop.Dock = DockStyle.Top

        ' Create a MenuStrip control with a new window.
        Dim ms As New MenuStrip()
        'Create The File menu
        Dim fileMenu As New ToolStripMenuItem("File")
        Dim fmSavereport As New ToolStripMenuItem("Save Report", Nothing, New EventHandler(AddressOf fmSavereport_Click))
        Dim fmEmailreport As New ToolStripMenuItem("Email Report", Nothing, New EventHandler(AddressOf fmEmailreport_Click))
        fileMenu.DropDownItems.Add(fmEmailreport)
        fileMenu.DropDownItems.Add(fmSavereport)
        CType(fileMenu.DropDown, ToolStripDropDownMenu).ShowImageMargin = True
        CType(fileMenu.DropDown, ToolStripDropDownMenu).ShowCheckMargin = True
        'Create the Actions menu
        Dim actionMenu As New ToolStripMenuItem("Actions")
        Dim amComparefiles As New ToolStripMenuItem("Compare Files", Nothing, New EventHandler(AddressOf amComparefiles_Click))
        Dim amRenamefiles As New ToolStripMenuItem("Rename Files", Nothing, New EventHandler(AddressOf amRenamefiles_Click))
        actionMenu.DropDownItems.Add(amComparefiles)
        actionMenu.DropDownItems.Add(amRenamefiles)
        CType(actionMenu.DropDown, ToolStripDropDownMenu).ShowImageMargin = True
        CType(actionMenu.DropDown, ToolStripDropDownMenu).ShowCheckMargin = True
        'Create Help menu
        Dim helpMenu As New ToolStripMenuItem("Help")
        Dim hmHowto As New ToolStripMenuItem("How To", Nothing, New EventHandler(AddressOf hmHowto_Click))
        Dim hmAbout As New ToolStripMenuItem("About", Nothing, New EventHandler(AddressOf hmAbout_Click))
        helpMenu.DropDownItems.Add(hmHowto)
        helpMenu.DropDownItems.Add(hmAbout)
        CType(helpMenu.DropDown, ToolStripDropDownMenu).ShowImageMargin = True
        CType(helpMenu.DropDown, ToolStripDropDownMenu).ShowCheckMargin = True

        ' Assign the ToolStripMenuItem that displays 
        ' the list of child forms.
        ms.MdiWindowListItem = fileMenu

        ' Add the window ToolStripMenuItem to the MenuStrip.
        ms.Items.Add(fileMenu)
        ms.Items.Add(actionMenu)
        ms.Items.Add(helpMenu)
        ' Dock the MenuStrip to the top of the form.
        ms.Dock = DockStyle.Top

        ' The Form.MainMenuStrip property determines the merge target.
        Me.MainMenuStrip = ms

        ' Add the ToolStripPanels to the form in reverse order.
        Me.Controls.Add(tspTop)

        ' Add the MenuStrip last.
        ' This is important for correct placement in the z-order.
        Me.Controls.Add(ms)
        Me.SizeGripStyle = Windows.Forms.SizeGripStyle.Show
        ' This call is required for Windows Form Designer support.
        InitializeComponent()
    End Sub

    
    ' Required designer variable.
    Private components As System.ComponentModel.Container

    ' Declare variables.
    Private tablfRadioButton2 As System.Windows.Forms.RadioButton
    Private tablfRadioButton1 As System.Windows.Forms.RadioButton

    'Rename files Tab
    Private WithEvents tabrfCheckboxfolder2 As System.Windows.Forms.CheckBox
    Private WithEvents tabrfCheckboxfolder1 As System.Windows.Forms.CheckBox
    Private WithEvents tabrfButtonfolder As System.Windows.Forms.Button
    Private WithEvents tabrfListbox As System.Windows.Forms.ListBox
    Private tabrfLabelOR As System.Windows.Forms.Label
    Private tabrfLabelpreview As System.Windows.Forms.Label
    Private WithEvents tabrfStorenumTextbox As System.Windows.Forms.TextBox
    Private WithEvents tabrfexampleTextbox As System.Windows.Forms.TextBox
    Private WithEvents tabrfrenameButton As System.Windows.Forms.Button
    Private tabrfProgressbar As System.Windows.Forms.ProgressBar
    Private WithEvents tabrfcommitButton As System.Windows.Forms.Button
    Private WithEvents tabrfcancelButton As System.Windows.Forms.Button
    Private WithEvents bwRenamefiles As BackgroundWorker
    Private WithEvents tabrfCheckboxnewname As System.Windows.Forms.CheckBox
    Private tabrfLabelstorenum As System.Windows.Forms.Label
    Private tabrfLabelnewnamestyle As System.Windows.Forms.Label
    Private WithEvents bwListfiles As BackgroundWorker

    'Compare Files tab
    Private WithEvents tabcfCheckboxsubfiles As System.Windows.Forms.CheckBox
    Private WithEvents tabcfListboxfolder1 As System.Windows.Forms.ListBox
    Private WithEvents tabcfListboxfolder2 As System.Windows.Forms.ListBox
    Private WithEvents tabcfButtonfolder1 As System.Windows.Forms.Button
    Private WithEvents tabcfButtonfolder2 As System.Windows.Forms.Button
    Private WithEvents tabcfButtoncompare As System.Windows.Forms.Button
    Private WithEvents tabcfButtonrename As System.Windows.Forms.Button
    Private WithEvents tabcfButtonsave As System.Windows.Forms.Button
    Private WithEvents tabcfButtoncancel As System.Windows.Forms.Button
    Private WithEvents bwComparefolder1 As BackgroundWorker
    Private WithEvents bwComparefolder2 As BackgroundWorker
    Private WithEvents bwComparetimer As BackgroundWorker

    'the tab themselves
    Private WithEvents tabListfiles As System.Windows.Forms.TabPage
    Private WithEvents tabRenamefiles As System.Windows.Forms.TabPage
    Private WithEvents tabComparefiles As System.Windows.Forms.TabPage
    Private tabControl1 As System.Windows.Forms.TabControl





    ' This method is required for Designer support.
    Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container()

        Me.tabControl1 = New System.Windows.Forms.TabControl()
        
        tabControl1.Size = Me.ClientSize
        tabControl1.Top = Me.MainMenuStrip.Bottom
        tabControl1.Height = tabControl1.Height - Me.MainMenuStrip.Bottom
   
        tabControl1.Anchor = AnchorStyles.Bottom Or AnchorStyles.Left Or AnchorStyles.Right Or AnchorStyles.Top
        tabControl1.SelectedIndex = 0
        tabControl1.TabIndex = 0

        'tab Compare Files
        Me.tabComparefiles = New System.Windows.Forms.TabPage()
        tabComparefiles.Text = "Compare Files"
        ' inherited properties don't do anything.
        tabComparefiles.TabIndex = 0

        Me.tabcfButtonfolder1 = New System.Windows.Forms.Button()
        tabcfButtonfolder1.Location = New System.Drawing.Point(190, tabControl1.Top)
        tabcfButtonfolder1.Size = New System.Drawing.Size(218, 52)
        tabcfButtonfolder1.TabIndex = 1
        tabcfButtonfolder1.Text = "Folder1"

        Me.tabcfButtonfolder2 = New System.Windows.Forms.Button()
        tabcfButtonfolder2.Location = New System.Drawing.Point(tabcfButtonfolder1.Right + (tabcfButtonfolder1.Width / 2), tabControl1.Top)
        tabcfButtonfolder2.Size = New System.Drawing.Size(218, 52)
        tabcfButtonfolder2.TabIndex = 3
        tabcfButtonfolder2.Text = "Folder2"

        Me.tabcfCheckboxsubfiles = New System.Windows.Forms.CheckBox()
        tabcfCheckboxsubfiles.Location = New System.Drawing.Point(tabControl1.Left + 2, tabcfButtonfolder1.Bottom)
        tabcfCheckboxsubfiles.Text = "Compare Files in subfolders"
        tabcfCheckboxsubfiles.Size = New System.Drawing.Size(154, 18)
        tabcfCheckboxsubfiles.TabIndex = 0

        Me.tabcfButtoncompare = New System.Windows.Forms.Button()
        tabcfButtoncompare.Size = tabcfButtonfolder1.Size
        tabcfButtoncompare.Location = New System.Drawing.Point(fpxCenter(tabcfButtonfolder1.Right, tabcfButtonfolder2.Left) - tabcfButtoncompare.Width / 2, tabControl1.Bottom - tabcfButtoncompare.Height - Me.MainMenuStrip.Height - 28)
        tabcfButtoncompare.Text = "Compare Files"
        tabcfButtoncompare.TabIndex = 5

        Me.tabcfButtoncancel = New System.Windows.Forms.Button()
        tabcfButtoncancel.Size = tabcfButtonfolder1.Size
        tabcfButtoncancel.Location = New System.Drawing.Point(fpxCenter(tabcfButtonfolder1.Right, tabcfButtonfolder2.Left) - tabcfButtoncancel.Width / 2, tabControl1.Bottom - tabcfButtoncancel.Height - Me.MainMenuStrip.Height - 28)
        tabcfButtoncancel.Text = "Cancel"
        tabcfButtoncancel.TabIndex = 6

        Me.tabcfButtonsave = New System.Windows.Forms.Button()
        tabcfButtonsave.Size = tabcfButtonfolder1.Size
        tabcfButtonsave.Location = New System.Drawing.Point(fpxCenter(tabcfButtonfolder1.Right, tabcfButtonfolder2.Left) - tabcfButtonsave.Width / 2, tabControl1.Bottom - tabcfButtonsave.Height - Me.MainMenuStrip.Height - 28)
        tabcfButtonsave.Text = "Save Report"
        tabcfButtonsave.TabIndex = 7

        Dim lbHeight As Integer = tabcfButtoncompare.Top - tabcfButtonfolder1.Bottom - 16
        Dim windowtext As Color = Color.Black

        Me.tabcfListboxfolder1 = New System.Windows.Forms.ListBox()
        tabcfListboxfolder1.Location = New System.Drawing.Point(tabcfButtonfolder1.Left, tabcfButtonfolder1.Height + tabControl1.Top + 2)
        tabcfListboxfolder1.Size = New System.Drawing.Size(tabcfButtonfolder1.Width, lbHeight)
        tabcfListboxfolder1.TabIndex = 2
        tabcfListboxfolder1.SelectionMode = SelectionMode.MultiExtended
        tabcfListboxfolder1.Visible = True
        tabcfListboxfolder1.DrawMode = DrawMode.Normal
        tabcfListboxfolder1.ForeColor = windowtext
        tabcfListboxfolder1.HorizontalScrollbar = True

        Me.tabcfListboxfolder2 = New System.Windows.Forms.ListBox()
        tabcfListboxfolder2.Location = New System.Drawing.Point(tabcfButtonfolder2.Left, tabcfButtonfolder2.Height + tabControl1.Top + 2)
        tabcfListboxfolder2.Size = New System.Drawing.Size(tabcfButtonfolder2.Width, lbHeight)
        tabcfListboxfolder2.TabIndex = 4
        tabcfListboxfolder2.SelectionMode = SelectionMode.MultiExtended
        tabcfListboxfolder2.Visible = True
        tabcfListboxfolder2.DrawMode = DrawMode.Normal
        tabcfListboxfolder2.HorizontalScrollbar = True

        tabcfButtoncompare.Show()
        tabcfButtoncancel.Hide()
        tabcfButtonsave.Hide()

        'tab Rename Files
        Me.tabRenamefiles = New System.Windows.Forms.TabPage()
        tabRenamefiles.Text = "Rename Files"
        tabRenamefiles.TabIndex = 1

        Me.tabrfButtonfolder = New System.Windows.Forms.Button()
        tabrfButtonfolder.Location = New System.Drawing.Point(tabControl1.Left + tabControl1.Top, tabControl1.Top)
        tabrfButtonfolder.Size = tabcfButtonfolder1.Size
        tabrfButtonfolder.TabIndex = 0
        tabrfButtonfolder.Text = "BrowseFolder"

        Me.tabrfCheckboxfolder1 = New System.Windows.Forms.CheckBox()
        tabrfCheckboxfolder1.Location = New System.Drawing.Point(tabrfButtonfolder.Right + tabControl1.Top, tabrfButtonfolder.Top)
        tabrfCheckboxfolder1.Text = "Use Folder " & tabcfButtonfolder1.Text & " from Compare Tab"
        tabrfCheckboxfolder1.Size = New System.Drawing.Size(176, 32)
        tabrfCheckboxfolder1.AutoSize = True
        tabrfCheckboxfolder1.TabIndex = 1
        tabrfCheckboxfolder1.Visible = True

        Me.tabrfCheckboxfolder2 = New System.Windows.Forms.CheckBox()
        tabrfCheckboxfolder2.Location = New System.Drawing.Point(tabrfButtonfolder.Right + tabControl1.Top, tabrfButtonfolder.Bottom)
        tabrfCheckboxfolder2.Text = "Use Folder " & tabcfButtonfolder2.Text & " from Compare Tab"
        tabrfCheckboxfolder2.Size = tabrfCheckboxfolder1.Size
        tabrfCheckboxfolder2.AutoSize = True
        tabrfCheckboxfolder2.TabIndex = 2
        tabrfCheckboxfolder2.Visible = True

        Me.tabrfListbox = New System.Windows.Forms.ListBox()
        tabrfListbox.Location = New System.Drawing.Point(tabrfButtonfolder.Left, tabcfButtonfolder1.Bottom + tabControl1.Top)
        tabrfListbox.Size = New System.Drawing.Size(tabrfButtonfolder.Width, lbHeight)
        tabrfListbox.TabIndex = 3
        tabrfListbox.SelectionMode = SelectionMode.MultiExtended
        tabrfListbox.Visible = True
        tabrfListbox.DrawMode = DrawMode.Normal
        tabrfListbox.ForeColor = windowtext
        tabrfListbox.AllowDrop = True
        'Add define for DisplayName here so we'll see the file name strings in the listbox
        tabrfListbox.DisplayMember = "DisplayName"
        tabrfListbox.HorizontalScrollbar = True

        Me.tabrfLabelOR = New System.Windows.Forms.Label()
        tabrfLabelOR.Size = tabrfCheckboxfolder1.Size
        tabrfLabelOR.Location = New Point(tabrfButtonfolder.Right, fpxCenter(tabrfButtonfolder.Top, tabrfButtonfolder.Bottom))
        tabrfLabelOR.Text = "OR"
        tabrfLabelOR.Visible = True
        tabrfLabelOR.TabIndex = 4

        Me.tabrfLabelpreview = New System.Windows.Forms.Label()
        tabrfLabelpreview.Size = tabrfCheckboxfolder1.Size
        tabrfLabelpreview.Location = New Point(fpxCenter(tabrfListbox.Left, tabrfListbox.Right) - tabrfLabelpreview.Width / 2, tabrfListbox.Top - tabrfLabelpreview.Font.Height)
        tabrfLabelpreview.Text = "Rename Preview"
        tabrfLabelpreview.Visible = True
        tabrfLabelpreview.TabIndex = 5

        Me.tabrfStorenumTextbox = New System.Windows.Forms.TextBox()
        tabrfStorenumTextbox.Size = New Point(100, 20)
        tabrfStorenumTextbox.Location = New Point(tabrfListbox.Right + tabControl1.Top, tabrfListbox.Top)
        tabrfStorenumTextbox.TabIndex = 6
        tabrfStorenumTextbox.Name = "Enter Store Number"
        tabrfStorenumTextbox.AllowDrop = True

        Me.tabrfLabelstorenum = New System.Windows.Forms.Label()
        tabrfLabelstorenum.Size = tabrfCheckboxfolder1.Size
        tabrfLabelstorenum.Location = New Point(fpxCenter(tabrfStorenumTextbox.Left, tabrfStorenumTextbox.Right) + tabrfLabelstorenum.Width / 2, tabrfStorenumTextbox.Top)
        tabrfLabelstorenum.Text = "Store Number"
        tabrfLabelstorenum.Visible = True
        tabrfLabelstorenum.TabIndex = 12

        Me.tabrfexampleTextbox = New System.Windows.Forms.TextBox()
        tabrfexampleTextbox.Size = New Point(200, 20)
        tabrfexampleTextbox.Location = New Point(tabrfListbox.Right + tabControl1.Top, tabrfStorenumTextbox.Bottom + tabControl1.Top)
        tabrfexampleTextbox.TabIndex = 7
        tabrfexampleTextbox.Name = "Add an example for name matching"
        tabrfexampleTextbox.Font = New System.Drawing.Font(Font, FontStyle.Italic)
        tabrfexampleTextbox.Text = tabrfexampleTextbox.Name
        tabrfexampleTextbox.AllowDrop = True


        Me.tabrfrenameButton = New System.Windows.Forms.Button()
        tabrfrenameButton.Size = tabrfButtonfolder.Size
        tabrfrenameButton.Location = New Point(tabrfexampleTextbox.Left, tabrfexampleTextbox.Bottom + tabControl1.Top)
        tabrfrenameButton.TabIndex = 8
        tabrfrenameButton.Text = "Preview Rename Files"

        Me.tabrfcommitButton = New System.Windows.Forms.Button()
        tabrfcommitButton.Size = tabrfButtonfolder.Size
        tabrfcommitButton.Location = New Point(tabrfexampleTextbox.Left, tabrfrenameButton.Bottom)
        tabrfcommitButton.TabIndex = 9
        tabrfcommitButton.Text = "Commit Rename Files"

        Me.tabrfProgressbar = New System.Windows.Forms.ProgressBar()
        tabrfProgressbar.Size = New Size(tabrfButtonfolder.Width, Int(tabrfexampleTextbox.Height / 2))
        tabrfProgressbar.Location = New Point(tabrfListbox.Left, tabrfListbox.Bottom)
        tabrfProgressbar.Style = ProgressBarStyle.Continuous
        tabrfProgressbar.TabIndex = 10
        'USE INCREMENT TO STEP THE BAR, STEP MAXIMUM TO BE THE TOTAL NUM OF FILES TO GO THRU.


        Me.tabrfcancelButton = New System.Windows.Forms.Button()
        tabrfcancelButton.Size = tabrfButtonfolder.Size
        tabrfcancelButton.Location = tabrfrenameButton.Location
        tabrfcancelButton.TabIndex = 11
        tabrfcancelButton.Text = "Cancel"
        tabrfcancelButton.Hide()

        Me.tabrfCheckboxnewname = New System.Windows.Forms.CheckBox()
        tabrfCheckboxnewname.Location = New System.Drawing.Point(tabrfrenameButton.Right + tabControl1.Top, tabrfrenameButton.Bottom)
        tabrfCheckboxnewname.Text = "Check to use the new naming style"
        tabrfCheckboxnewname.Size = tabrfCheckboxfolder1.Size
        tabrfCheckboxnewname.AutoSize = True
        tabrfCheckboxnewname.TabIndex = 13
        tabrfCheckboxnewname.Visible = True

        'tab List Files
        Me.tabListfiles = New System.Windows.Forms.TabPage()
        tabListfiles.Text = "List Files"
        'tabListfiles.Size = New System.Drawing.Size(256, 214)
        tabListfiles.TabIndex = 2



        'Have to add stuff backwards so it displays correctly
        ' Adds controls to the second tab page.
        tabRenamefiles.Controls.Add(Me.tabrfLabelstorenum)
        tabRenamefiles.Controls.Add(Me.tabrfCheckboxnewname)
        tabRenamefiles.Controls.Add(Me.tabrfCheckboxfolder2)
        tabRenamefiles.Controls.Add(Me.tabrfCheckboxfolder1)
        tabRenamefiles.Controls.Add(Me.tabrfListbox)
        tabRenamefiles.Controls.Add(Me.tabrfButtonfolder)
        tabRenamefiles.Controls.Add(Me.tabrfLabelpreview)
        tabRenamefiles.Controls.Add(Me.tabrfLabelOR)
        tabRenamefiles.Controls.Add(Me.tabrfStorenumTextbox)
        tabRenamefiles.Controls.Add(Me.tabrfexampleTextbox)
        tabRenamefiles.Controls.Add(Me.tabrfrenameButton)
        tabRenamefiles.Controls.Add(Me.tabrfcommitButton)
        tabRenamefiles.Controls.Add(Me.tabrfProgressbar)
        tabRenamefiles.Controls.Add(Me.tabrfcancelButton)

        ' Adds controls to the third tab page.
        tabListfiles.Controls.Add(Me.tablfRadioButton2)
        tabListfiles.Controls.Add(Me.tablfRadioButton1)

        ' Adds controls to the first tab page.
        tabComparefiles.Controls.Add(Me.tabcfCheckboxsubfiles)
        tabComparefiles.Controls.Add(Me.tabcfButtonfolder1)
        tabComparefiles.Controls.Add(Me.tabcfButtonfolder2)
        tabComparefiles.Controls.Add(Me.tabcfListboxfolder1)
        tabComparefiles.Controls.Add(Me.tabcfListboxfolder2)
        tabComparefiles.Controls.Add(Me.tabcfButtonsave)
        tabComparefiles.Controls.Add(Me.tabcfButtoncancel)
        tabComparefiles.Controls.Add(Me.tabcfButtoncompare)
        tabComparefiles.Controls.Add(Me.tabcfButtonrename)

        ' Adds the TabControl to the form.
        Me.Controls.Add(tabControl1)

        ' Adds the tab pages to the TabControl.
        tabControl1.Controls.Add(Me.tabComparefiles)
        tabControl1.Controls.Add(Me.tabRenamefiles)
        tabControl1.Controls.Add(Me.tabListfiles)

        'define the backgroundwoorkers
        Me.bwComparefolder1 = New System.ComponentModel.BackgroundWorker
        'CType(Me.tabcfButtonfolder1, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.bwComparefolder1.WorkerReportsProgress = True
        Me.bwComparefolder1.WorkerSupportsCancellation = True

        Me.bwComparefolder2 = New System.ComponentModel.BackgroundWorker
        'CType(Me.tabcfButtonfolder1, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.bwComparefolder2.WorkerReportsProgress = True
        Me.bwComparefolder2.WorkerSupportsCancellation = True

        Me.bwComparetimer = New System.ComponentModel.BackgroundWorker
        'CType(Me.tabcfButtonfolder1, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.bwComparetimer.WorkerReportsProgress = True
        Me.bwComparetimer.WorkerSupportsCancellation = True

        Me.bwRenamefiles = New System.ComponentModel.BackgroundWorker
        Me.bwRenamefiles.WorkerReportsProgress = True
        Me.bwRenamefiles.WorkerSupportsCancellation = True

        Me.bwListfiles = New System.ComponentModel.BackgroundWorker
        Me.bwListfiles.WorkerReportsProgress = True
        Me.bwListfiles.WorkerSupportsCancellation = True

    End Sub


    Private Function fpxCenter(ByVal x1 As Integer, ByVal x2 As Integer)
        Dim pxLeftright As Double
        pxLeftright = (x2 - x1) / 2
        fpxCenter = x1 + Int(pxLeftright)
    End Function

    'button clicks section

    Private Sub tabRenamefiles_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles tabRenamefiles.Click
        tabRenamefiles.Show()
    End Sub
    ' This event handler is invoked when 
    ' the "Save Report" ToolStripMenuItem is clicked.
    ' property to the main form.
    Private Sub fmSavereport_Click(ByVal sender As Object, ByVal e As EventArgs)
        subSavecompare()
    End Sub
    Private Sub fmEmailreport_Click(ByVal sender As Object, ByVal e As EventArgs)
        'open email composer for current email client
        'add the compare report to the body of the email
    End Sub
    Private Sub amComparefiles_Click(ByVal sender As Object, ByVal e As EventArgs)
        'switch to compare tab
        'if already on the tabpage then do compare
        'but check if the folder paths are selected first
    End Sub
    Private Sub amRenamefiles_Click(ByVal sender As Object, ByVal e As EventArgs)
        'similar to the above
    End Sub
    Private Sub hmHowto_Click(ByVal sender As Object, ByVal e As EventArgs)
        'do what?
    End Sub
    Private Sub hmAbout_Click(ByVal sender As Object, ByVal e As EventArgs)
        'say who made this.  and version info
        MsgBox(Me.ProductName & Chr(13) & "Version: " & Me.ProductVersion & Chr(13) & _
               "Copyright 2010 Brian L. Crawford" & Chr(13) & Chr(13) & _
                "Licensed under the Apache License, Version 2.0 (the ""License"");" & Chr(13) & _
        "you may not use this file except in compliance with the License." & Chr(13) & _
        "You may obtain a copy of the License at" & Chr(13) & _
         Chr(13) & _
            "http://www.apache.org/licenses/LICENSE-2.0" & Chr(13) & _
         Chr(13) & _
        "Unless required by applicable law or agreed to in writing, software" & Chr(13) & _
        "distributed under the License is distributed on an ""AS IS"" BASIS," & Chr(13) & _
        "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied." & Chr(13) & _
        "See the License for the specific language governing permissions and" & Chr(13) & _
        "limitations under the License." & Chr(13) & _
        Chr(13) & _
        "This software uses Microsoft .Net framework used with permission from" & Chr(13) & _
        "Microsoft. Microsoft, .Net Framework, Visual Studio, Visual Basic, Visual C++" & Chr(13) & _
        "remain the trademark and copyright of Microsoft and are subject to their" & Chr(13) & _
        "individual licenses.")
    End Sub

    Private Sub tabcfButtonfolder1_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
        Handles tabcfButtonfolder1.Click
        resetfolderstatus()
        tabcfButtonfolder1.Text = GetBrowse("Select the Reference folder; usually the EDDS/OTP folder", tabcfButtonfolder2.Text)
        Savepath = tabcfButtonfolder1.Text
        tabcfButtoncompare.Show()
        tabcfButtoncancel.Hide()
        tabcfButtonsave.Hide()
    End Sub

    Private Sub tabcfButtonfolder2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles tabcfButtonfolder2.Click
        resetfolderstatus()
        tabcfButtonfolder2.Text = GetBrowse("Select the Folder containing files to compare against the EDDS folder", tabcfButtonfolder1.Text)
        tabcfButtoncompare.Show()
        tabcfButtoncancel.Hide()
        tabcfButtonsave.Hide()
    End Sub

    Private Sub tabcfButtonfolder1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles tabcfButtonfolder1.TextChanged
        'tabrfCheckboxfolder1.Text = "Use Folder " & tabcfButtonfolder1.Text & " from Compare Tab"
    End Sub

    Private Sub tabcfButtonfolder2_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles tabcfButtonfolder2.TextChanged
        'Me.tabrfCheckboxfolder2.Text = "Use Folder " & tabcfButtonfolder2.Text & " from Compare Tab"
    End Sub

    Private Sub tabcfCheckboxsubfiles_Checked(ByVal sender As Object, ByVal e As System.EventArgs) Handles tabcfCheckboxsubfiles.CheckedChanged
        checkboxstatus = sender.checked()
    End Sub


    Private Sub tabcfButtoncompare_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles tabcfButtoncompare.Click
        'first check if the PATH is set for each of the folder classes
        If tabcfButtonfolder1.Text = Nothing Then
            'add something to do when path is null
            Exit Sub
        ElseIf tabcfButtonfolder2.Text = Nothing Then
            'add something to do when path is default
            Exit Sub
        ElseIf tabcfButtonfolder1.Text = "Folder1" Then
            'add something to do when path is null
            Exit Sub
        ElseIf tabcfButtonfolder2.Text = "Folder2" Then
            'add something to do when path is default
            Exit Sub
        End If
        'Need to make sure that the listboxes are clear and that all of the objects are ready for the search

        If checkboxstatus = True Then
            bwComparefolder1.RunWorkerAsync(tabcfButtonfolder1.Text) 'uncomment for multi-threading
            bwComparefolder2.RunWorkerAsync(tabcfButtonfolder2.Text)   'uncomment for multi-threading  
            bwComparetimer.RunWorkerAsync()                     'uncomment for multi-threading
        Else
            'do_comparefiles()  'old single threaded
            bwComparefolder1.RunWorkerAsync(tabcfButtonfolder1.Text) 'uncomment for multi-threading
            bwComparefolder2.RunWorkerAsync(tabcfButtonfolder2.Text)   'uncomment for multi-threading  
            bwComparetimer.RunWorkerAsync()                     'uncomment for multi-threading
        End If
        ' button flip
        tabcfButtoncompare.Hide()
        tabcfButtoncancel.Show()
        tabcfButtonsave.Hide()
    End Sub
    Private Sub tabcfButtoncancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles tabcfButtoncancel.Click
        Me.bwComparefolder1.CancelAsync()
        Me.bwComparefolder2.CancelAsync()
        Me.bwComparetimer.CancelAsync()
    End Sub
    Private Sub tabcfButtonsave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles tabcfButtonsave.Click
        subSavecompare()
    End Sub

    Private Sub tabrfButtonfolder_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles tabrfButtonfolder.Click
        'uncheck the checkbox - we can only do one of the three at a time.  this has to be clear to the user
        tabrfCheckboxfolder1.Checked = False
        tabrfCheckboxfolder2.Checked = False
        'make sure the list box is clear
        If tabrfListbox.Items.Count() > 0 Then tabrfListbox.Items.Clear()
        'get a path
        Dim strPath As String
        tabrfButtonfolder.Text = BrowseFolder.GetBrowse()
        strPath = tabrfButtonfolder.Text
        'start up the background process to list files using the path
        If strPath = Nothing Then Exit Sub
        tabrfrenameButton.Enabled = False
        bwListfiles.RunWorkerAsync(strPath)
    End Sub

    Private Sub tabrfexampleTextbox_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles tabrfexampleTextbox.Click
        Cleartextformatting(tabrfexampleTextbox)
    End Sub


    Private Sub tabrfCheckboxfolder1_CheckStateChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles tabrfCheckboxfolder1.CheckStateChanged
        If tabrfCheckboxfolder1.Checked = False Then Exit Sub
        'rest the other two buttons when this one is checked
        tabrfButtonfolder.Text = "Browse to Folder"
        tabrfCheckboxfolder2.Checked = False
        'make sure the list box is clear
        If tabrfListbox.Items.Count() > 0 Then tabrfListbox.Items.Clear()
        'get files from compare folder 1
        tabrfListbox.Items.AddRange(tabcfListboxfolder1.Items)
    End Sub

    Private Sub tabrfCheckboxfolder2_CheckStateChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles tabrfCheckboxfolder2.CheckStateChanged
        If tabrfCheckboxfolder2.Checked = False Then Exit Sub
        'rest the other two buttons when this one is checked
        tabrfButtonfolder.Text = "Browse to Folder"
        tabrfCheckboxfolder1.Checked = False
        'make sure the listbox is clear
        If tabrfListbox.Items.Count() > 0 Then tabrfListbox.Items.Clear()
        'get files from compare folder 1
        tabrfListbox.Items.AddRange(tabcfListboxfolder2.Items)
    End Sub
    Private indexOfItemUnderMouseToDrag As Integer
    Private indexOfItemUnderMouseToDrop As Integer
    Private dragBoxFromMouseDown As Rectangle
    Private screenOffset As Point
    Private Sub tabrflistbox_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles tabrflistbox.MouseDown

        ' Get the index of the item the mouse is below.
        indexOfItemUnderMouseToDrag = tabrflistbox.IndexFromPoint(e.X, e.Y)

        If (indexOfItemUnderMouseToDrag <> ListBox.NoMatches) Then

            ' Remember the point where the mouse down occurred. The DragSize indicates
            ' the size that the mouse can move before a drag event should be started.                
            Dim dragSize As Size = SystemInformation.DragSize

            ' Create a rectangle using the DragSize, with the mouse position being
            ' at the center of the rectangle.
            dragBoxFromMouseDown = New Rectangle(New Point(e.X - (dragSize.Width / 2), _
                                                            e.Y - (dragSize.Height / 2)), dragSize)
        Else
            ' Reset the rectangle if the mouse is not over an item in the ListBox.
            dragBoxFromMouseDown = Rectangle.Empty
        End If

    End Sub

    Private Sub tabrflistbox_MouseUp(ByVal sender As Object, ByVal e As MouseEventArgs) Handles tabrflistbox.MouseUp

        ' Reset the drag rectangle when the mouse button is raised.
        dragBoxFromMouseDown = Rectangle.Empty
    End Sub

    Private Sub tabrflistbox_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs) Handles tabrflistbox.MouseMove

        If ((e.Button And MouseButtons.Left) = MouseButtons.Left) Then

            ' If the mouse moves outside the rectangle, start the drag.
            If (Rectangle.op_Inequality(dragBoxFromMouseDown, Rectangle.Empty) And _
                Not dragBoxFromMouseDown.Contains(e.X, e.Y)) Then

                ' The screenOffset is used to account for any desktop bands 
                ' that may be at the top or left side of the screen when 
                ' determining when to cancel the drag drop operation.
                screenOffset = SystemInformation.WorkingArea.Location

                ' Proceed with the drag-and-drop, passing in the list item.                    
                Dim dropEffect As DragDropEffects = tabrfListbox.DoDragDrop(tabrfListbox.Items(indexOfItemUnderMouseToDrag), _
                                                                              DragDropEffects.All Or DragDropEffects.Link)

                '' If the drag operation was a move then remove the item.
                'If (dropEffect = DragDropEffects.Move) Then
                '    tabrflistbox.Items.RemoveAt(indexOfItemUnderMouseToDrag)

                '    ' Select the previous item in the list as long as the list has an item.
                '    If (indexOfItemUnderMouseToDrag > 0) Then
                '        tabrflistbox.SelectedIndex = indexOfItemUnderMouseToDrag - 1

                '    ElseIf (tabrflistbox.Items.Count > 0) Then
                '        ' Selects the first item.
                '        tabrflistbox.SelectedIndex = 0
                '    End If
                'End If

                '' Dispose the cursors since they are no longer needed.
                'If (Not MyNormalCursor Is Nothing) Then _
                '    MyNormalCursor.Dispose()

                'If (Not MyNoDropCursor Is Nothing) Then _
                '    MyNoDropCursor.Dispose()

            End If
        End If
    End Sub
    Private Sub tabrflistbox_GiveFeedback(ByVal sender As Object, ByVal e As GiveFeedbackEventArgs) Handles tabrflistbox.GiveFeedback

        e.UseDefaultCursors = True

    End Sub

    Private Sub tabrflistbox_QueryContinueDrag(ByVal sender As Object, ByVal e As QueryContinueDragEventArgs) Handles tabrfListbox.QueryContinueDrag
        ' Cancel the drag if the mouse moves off the form.
        Dim lb As ListBox = CType(sender, System.Windows.Forms.ListBox)

        If (lb IsNot Nothing) Then

            Dim f As Form = lb.FindForm()

            ' Cancel the drag if the mouse moves off the form. The screenOffset
            ' takes into account any desktop bands that may be at the top or left
            ' side of the screen.
            If (((Control.MousePosition.X - screenOffset.X) < f.DesktopBounds.Left) Or _
                ((Control.MousePosition.X - screenOffset.X) > f.DesktopBounds.Right) Or _
                ((Control.MousePosition.Y - screenOffset.Y) < f.DesktopBounds.Top) Or _
                ((Control.MousePosition.Y - screenOffset.Y) > f.DesktopBounds.Bottom)) Then

                e.Action = DragAction.Cancel
            End If
        End If
    End Sub

    Private Sub tabrfexampletextbox_DragOver(ByVal sender As Object, ByVal e As DragEventArgs) Handles tabrfexampleTextbox.DragOver
        'clear the textbox formatting
        Cleartextformatting(tabrfexampleTextbox)

        ' Determine whether string data exists in the drop data. If not, then
        ' the drop effect reflects that the drop cannot occur.

        If Not (e.Data.GetDataPresent(GetType(FileCompare.classListboxObject))) Then

            e.Effect = DragDropEffects.None

            Return

        End If

        ' Set the effect based upon the KeyState.
        If ((e.KeyState And (8 + 32)) = (8 + 32) And _
            (e.AllowedEffect And DragDropEffects.Link) = DragDropEffects.Link) Then
            ' Link drag-and-drop effect.
            e.Effect = DragDropEffects.Link

        ElseIf ((e.KeyState And 32) = 32 And _
            (e.AllowedEffect And DragDropEffects.Link) = DragDropEffects.Link) Then

            ' ALT KeyState for link.
            e.Effect = DragDropEffects.Link

        ElseIf ((e.KeyState And 4) = 4 And _
            (e.AllowedEffect And DragDropEffects.Move) = DragDropEffects.Move) Then

            ' SHIFT KeyState for move.
            e.Effect = DragDropEffects.Move

        ElseIf ((e.KeyState And 8) = 8 And _
            (e.AllowedEffect And DragDropEffects.Copy) = DragDropEffects.Copy) Then

            ' CTL KeyState for copy.
            e.Effect = DragDropEffects.Copy

        ElseIf ((e.AllowedEffect And DragDropEffects.Copy) = DragDropEffects.Copy) Then

            ' By default, the drop action should be copy, if allowed.
            e.Effect = DragDropEffects.Copy

        Else
            e.Effect = DragDropEffects.None
        End If
        'clear text box and drop everything
        tabrfexampleTextbox.Clear()
        Dim MyFileNameStr As Object = e.Data.GetData(GetType(FileCompare.classListboxObject))
        MyFileNameStr = CType(MyFileNameStr, classListboxObject)
        tabrfexampleTextbox.Text = MyFileNameStr.DisplayName()
    End Sub

    Private Sub tabrfexampletextbox_DragDrop(ByVal sender As Object, ByVal e As DragEventArgs) Handles tabrfexampleTextbox.DragDrop
        ' Ensures that the list item index is contained in the data.

        If (e.Data.GetDataPresent(GetType(classListboxObject))) Then
            Dim MyFileNameStr As Object = e.Data
            MyFileNameStr = CType(MyFileNameStr, classListboxObject)
            Dim mystring As String = MyFileNameStr.DisplayName()
            ' Perform drag-and-drop, depending upon the effect.
            If (e.Effect = DragDropEffects.Copy Or _
                e.Effect = DragDropEffects.Move) Then
                tabrfexampleTextbox.Text = mystring
                '' Insert the item.
                'If (indexOfItemUnderMouseToDrop <> ListBox.NoMatches) Then
                '    tabrfexampleTextbox.Text.Insert(indexOfItemUnderMouseToDrop, item)
                'Else
                '    'tabrfexampleTextbox.Items.Add(item)

                'End If
            End If
            ' Reset the label text.

        End If

    End Sub


    Private Sub tabrfrenameButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles tabrfrenameButton.Click
        If tabrfListbox.Items.Count <> 0 Then 'works for when we have 1 or more items
            'rename the items
            Dim mylistboxholder As New ListBox
            mylistboxholder.Items.AddRange(tabrfListbox.Items())
            tabrfListbox.Items.Clear()
            If tabrfCheckboxnewname.CheckState = CheckState.Checked Then
                MsgBox(RENAMER.fnRenameList2(mylistboxholder, tabrfStorenumTextbox.Text, tabrfexampleTextbox.Text, strDefaultRemove, True), _
                        MsgBoxStyle.DefaultButton1, "Badly named files")
            Else
                RENAMER.fnRenameList2(mylistboxholder, tabrfStorenumTextbox.Text, tabrfexampleTextbox.Text, strDefaultRemove)
            End If
            For Each item In mylistboxholder.Items
                fileAddtoCollection(tabrfListbox, item)
            Next
            tabrfListbox.Refresh()
            
        End If
    End Sub

    Private Sub tabrfStorenumTextbox_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles tabrfStorenumTextbox.Enter
        tabrfrenameButton_Click(sender, e)
    End Sub

    Private Sub tabrfStorenumTextbox_MouseHover(ByVal sender As Object, ByVal e As System.EventArgs) Handles tabrfStorenumTextbox.MouseHover
        Cleartextformatting(tabrfStorenumTextbox)
    End Sub

    Private Sub tabrfStorenumTextbox_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles tabrfStorenumTextbox.TextChanged
        ''just rename stuff on this tread for now.
        ''Dim MyResult As New System.Windows.Forms.ListBox()
        'Dim MyResult As New ListBox
        'MyResult = RENAMER.fnRenameList(tabrfListbox, tabrfStorenumTextbox.Text, tabrfexampleTextbox.Text, strDefaultRemove)
        ''MyResult = CType(e.Result, ListBox.ObjectCollection)
        'If MyResult.Items.Count <> tabrfListbox.Items.Count Then
        '    'something bad happened
        '    MsgBox("Something really bad happened to your file list" & Chr(13) _
        '           & "and all you can do is click OK.", MsgBoxStyle.OkOnly, "Holy Shit!")
        'Else
        '    'clear list and update it with the renamed files
        '    tabrfListbox.BeginUpdate()
        '    'tabrfListbox.Items.Clear()
        '    For Each i In MyResult.Items
        '        COMPAREFUNCTIONS.fileAddtoCollection(tabrfListbox, CType(i, classListboxObject))
        '    Next
        '    tabrfListbox.EndUpdate()
        'End If
        ' ''uncomment block later for multitreading
        ' ''check to see if the background worker is running - can't instanitate multiple instances of the same worker
        ''If bwRenamefiles.IsBusy = True Then
        ''    bwRenamefiles.CancelAsync()
        ''End If
        ' ''wait on the race condition
        ''Do While bwRenamefiles.IsBusy = True
        ''    'something.  do a counter sub which will return an error if the worker doesn't
        ''    'cancel in a reasonable amount of time
        ''Loop
        ' ''rename using the new text
        ''bwRenamefiles.RunWorkerAsync()
        ' ''end of block
    End Sub





    'the blue collar section
    Private Sub subSavecompare()
        Dim fc As String
        fc = "The Reference folder is " & tabcfButtonfolder1.Text & vbCrLf & "The following files in " & Chr(33) & tabcfButtonfolder2.Text & Chr(33) & " don't seem to match files found in the reference folder: " & vbCrLf & vbCrLf
        For Each fn3 In tabcfListboxfolder2.Items
            fc = fc & fn3.name & vbCrLf
        Next
        WriteLog((fc), Savepath)
        'don't clear the lists here, someone might want to save the result a couple of times
    End Sub

    Private Sub bwComparefolder1_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles bwComparefolder1.DoWork
        
        If e.Argument = Nothing Then
            'For the case when the subfiles isn't checked.  probably should use the value of the check box
            'rather than testing to see if i'm passing folders to the backgroundworker.
            COMPAREFUNCTIONS.collect_files(e.Argument, sender, e)
        Else
            e.Result = COMPAREFUNCTIONS.collect_subfiles(e.Argument, sender, e, checkboxstatus)

        End If
    End Sub

    Private Sub bwComparefolder1_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bwComparefolder1.ProgressChanged
        'add results of the search to the listbox
        Dim item As FileInfo = CType(e.UserState, FileInfo)
        Dim itemobj As classListboxObject = New classListboxObject(item.Name, item)
        fileAddtoCollection(tabcfListboxfolder1, itemobj)
    End Sub

    ' This event handler deals with the results of the
    ' background operation.
    Private Sub bwComparefolder1_RunWorkerCompleted( _
    ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) _
    Handles bwComparefolder1.RunWorkerCompleted

        ' First, handle the case where an exception was thrown.
        If (e.Error IsNot Nothing) Then
            MessageBox.Show(e.Error.Message)
        ElseIf e.Cancelled Then
            ' Next, handle the case where the user canceled the 
            ' operation.
            ' Note that due to a race condition in 
            ' the DoWork event handler, the Cancelled
            ' flag may not have been set, even though
            ' CancelAsync was called.
            tabcfListboxfolder1.Items.Clear()

        Else
            ' Finally, handle the case where the operation succeeded.
            folder1status = e.Result
        End If

    End Sub

    Private Sub bwComparefolder2_DoWork(ByVal sender As System.Object, ByVal e As DoWorkEventArgs) Handles bwComparefolder2.DoWork
        '' Assign the result of the computation
        '' to the Result property of the DoWorkEventArgs
        '' object. This is will be available to the 
        '' RunWorkerCompleted eventhandler.


        If e.Argument = Nothing Then
            'For the case when the subfiles isn't checked.  probably should use the value of the check box
            'rather than testing to see if i'm passing folders to the backgroundsender.
            COMPAREFUNCTIONS.collect_files(e.Argument, sender, e)
        Else
            e.Result = COMPAREFUNCTIONS.collect_subfiles(e.Argument, sender, e, checkboxstatus)
            
        End If
    End Sub

    Private Sub bwComparefolder2_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bwComparefolder2.ProgressChanged
        'add results of the search to the listbox
        Dim item As FileInfo = CType(e.UserState, FileInfo)
        Dim itemobj As classListboxObject = New classListboxObject(item.Name, item)
        fileAddtoCollection(tabcfListboxfolder2, itemobj)
    End Sub

    ' This event handler deals with the results of the
    ' background operation.
    Private Sub bwComparefolder2_RunWorkerCompleted(ByVal sender As Object, _
                                                    ByVal e As RunWorkerCompletedEventArgs) Handles bwComparefolder2.RunWorkerCompleted

        ' First, handle the case where an exception was thrown.
        If (e.Error IsNot Nothing) Then
            MessageBox.Show(e.Error.Message)
        ElseIf e.Cancelled Then
            ' Next, handle the case where the user canceled the 
            ' operation.
            ' Note that due to a race condition in 
            ' the DoWork event handler, the Cancelled
            ' flag may not have been set, even though
            ' CancelAsync was called.
            tabcfListboxfolder2.Items.Clear()
        Else
            ' Finally, handle the case where the operation succeeded.
            folder2status = e.Result
        End If

        'can do something here like enabling buttons
    End Sub
    Private Sub bwComparetimer_DoWork(ByVal sender As System.Object, ByVal e As DoWorkEventArgs) Handles bwComparetimer.DoWork
        ' starts the timer in the background
        ' the timer will check periodically to see if the file collection
        ' threads have finished
        ' I could have used the finished event from each of the separate treads
        ' but it was easier just to make a timer to keep checking up on them since they typically
        ' execute very fast
        waitonthreads(sender, e)
    End Sub

    ' This event handler deals with the results of the
    ' background operation.
    Private Sub bwComparetimer_RunWorkerCompleted( _
    ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) _
    Handles bwComparetimer.RunWorkerCompleted

        ' First, handle the case where an exception was thrown.
        If (e.Error IsNot Nothing) Then
            MessageBox.Show(e.Error.Message)

        ElseIf e.Cancelled Then
            ' Next, handle the case where the user canceled the 
            ' operation.
            ' Note that due to a race condition in 
            ' the DoWork event handler, the Cancelled
            ' flag may not have been set, even though
            ' CancelAsync was called.
            resetfolderstatus()
            tabcfButtoncompare.Show()
            tabcfButtoncancel.Hide()
            tabcfButtonsave.Hide()
        Else
            ' Finally, handle the case where the operation succeeded.
            'Now to compare files in the two boxes and update the display to show what we find.
            'Will need to clear the contents of the lists before we try to start a new search.
            'enable the button on form2 to compare the files.
            CompareFiles(tabcfListboxfolder1, tabcfListboxfolder2, tabcfListboxfolder2.Items.Count - 1)
            tabcfButtoncompare.Hide()
            tabcfButtoncancel.Hide()
            tabcfButtonsave.Show()

        End If
        'add controls for buttons
       
    End Sub


    'this block needs to become a timer or method which will check periodically if the two 
    'threads have finished before running the comparison
    Dim myTimer As New System.Windows.Forms.Timer()
    Dim alarmCounter As Integer = 1
    Dim exitFlag As Boolean = False

    ' This is the method to run when the timer is raised.
    Sub TimerEventProcessor(ByVal myObject As Object, ByVal myEventArgs As EventArgs)
        ' Stops the timer.
        myTimer.Stop()

        ' check if background threads finished
        If folder1status = True Then
            If folder2status = True Then
                exitFlag = True
            End If
        Else

            ' Restarts the timer and increments the counter.
            alarmCounter += 1
            myTimer.Enabled = True
        End If
    End Sub

    Public Function waitonthreads(ByVal worker As BackgroundWorker, ByVal e As DoWorkEventArgs)
        Try
            'check for cancellation
            If worker.CancellationPending = True Then Exit Function
            ' Adds the event and the event handler for the method that will
            ' process the timer event to the timer.
            AddHandler myTimer.Tick, AddressOf TimerEventProcessor
            ' Sets the timer interval to 1/10 seconds.
            myTimer.Interval = 10
            myTimer.Start()
            ' Runs the timer, and raises the event.
            While exitFlag = False
                'check for cancellation
                If worker.CancellationPending = True Then Exit Function
                ' Processes all the events in the queue.
                Application.DoEvents()
            End While
        Catch ex As Exception
            MessageBox.Show(ex.Message.ToString)
        End Try
    End Function

    Sub resetfolderstatus()
        'clear items in my folder collections
        folder1status = False
        folder2status = False
        exitFlag = False
        tabcfListboxfolder1.Items.Clear()
        tabcfListboxfolder2.Items.Clear()
        tabcfListboxfolder1.Refresh()
        tabcfListboxfolder2.Refresh()

    End Sub
    Sub labelposition(ByVal myLabel As Label, ByVal x As Integer, ByVal y As Integer)
        myLabel.Location = New Point(x, y)
        myLabel.Width = Me.Width - 12
    End Sub


    Private Sub bwRenamefiles_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bwRenamefiles.DoWork

        If e.Argument = Nothing Then
            e.Result = RENAMER.fnRenameList(tabrfListbox, tabrfStorenumTextbox.Text, tabrfexampleTextbox.Text, strDefaultRemove)
            'tabrfListbox.Invoke(AddressOf tabrfListbox.Refresh) 'crap, much too complex just refresh once completed
        Else

        End If
    End Sub

    Private Sub bwRenamefiles_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bwRenamefiles.ProgressChanged

    End Sub

    Private Sub bwRenamefiles_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bwRenamefiles.RunWorkerCompleted
        Dim MyResult As New ListBox
        MyResult.Items.AddRange(e.Result)
        If MyResult.Items.Count <> tabrfListbox.Items.Count Then
            'something bad happened
            MsgBox("Something really bad happened to your file list" & Chr(13) _
                   & "and all you can do is click OK.", MsgBoxStyle.OkOnly, "Holy Shit!")
        Else
            'update the list with the renamed files
            tabrfListbox.BeginUpdate()

            For Each i In MyResult.Items
                COMPAREFUNCTIONS.fileAddtoCollection(tabrfListbox, CType(i, classListboxObject))
            Next
            tabrfListbox.EndUpdate()
        End If
    End Sub

    Public Sub fnRenamelistitems(ByVal item As String, ByVal index As Integer)
        tabrfListbox.Items.RemoveAt(index)
        tabrfListbox.Items.Insert(index, item)
    End Sub

    Private Sub bwListfiles_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bwListfiles.DoWork
        ' Get the BackgroundWorker object that raised this event.
        'Dim worker As BackgroundWorker = _
        '    CType(sender, BackgroundWorker)
        'don't want to create a new address just to hold the argument and it saves
        'on a processor cycle
        If e.Argument = Nothing Then
            'No files to process in the Listbox
            Exit Sub
        Else
            Dim MyDirectory As New DirectoryInfo(e.Argument)
            COMPAREFUNCTIONS.collect_files(MyDirectory, sender, e)

        End If
    End Sub

    Private Sub bwListfiles_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bwListfiles.ProgressChanged
        Dim item As FileInfo = CType(e.UserState, FileInfo)
        Dim itemobj As New classListboxObject(item.Name, item)
        fileAddtoCollection(tabrfListbox, itemobj)


    End Sub


    Private Sub bwListfiles_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bwListfiles.RunWorkerCompleted

        ' First, handle the case where an exception was thrown.
        If (e.Error IsNot Nothing) Then
            MessageBox.Show(e.Error.Message)

        ElseIf e.Cancelled Then
            ' Next, handle the case where the user canceled the 
            ' operation.
            ' Note that due to a race condition in 
            ' the DoWork event handler, the Cancelled
            ' flag may not have been set, even though
            ' CancelAsync was called.
            
        Else
            ' Finally, handle the case where the operation succeeded.
          
        End If
        'add controls for buttons        

        ' Enable the Start button.
        tabrfrenameButton.Enabled = True
        ' Disable the Cancel button.

    End Sub

   
    Private Sub tabcfListboxfolder1_MouseCaptureChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles tabcfListboxfolder1.MouseCaptureChanged

    End Sub

    Private Sub tabrfcommitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles tabrfcommitButton.Click
        'really rename files
        If tabrfListbox.Items.Count <> 0 Then 'works for when we have 2 or more items
            'rename the items
            Dim mylistboxholder As New ListBox
            'mylistboxholder = RENAMER.fnRenameList(tabrfListbox, tabrfStorenumTextbox.Text, tabrfexampleTextbox.Text, strDefaultRemove)
            mylistboxholder.Items.AddRange(tabrfListbox.Items)
            'tabrfListbox.Items.AddRange(mylistboxholder.Items)
            For Each item In mylistboxholder.Items
                RENAMER.fnrenamefile(item)
            Next
        End If
    End Sub

    Private Sub Cleartextformatting(ByRef Mytextbox As TextBox)
        If Mytextbox.Font.Italic = False Then Exit Sub
        Mytextbox.Clear()
        Mytextbox.Font = New System.Drawing.Font(Font, FontStyle.Regular)
    End Sub
 
    Private Sub tabrfexampleTextbox_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles tabrfexampleTextbox.Enter
        tabrfexampleTextbox.Text = StrEDDSfilenameparser(tabrfexampleTextbox.Text, True)
        tabrfrenameButton_Click(sender, e)
    End Sub
End Class